<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./vue.js"></script>
</head>

<body>
    <div id="app">
        <q-header></q-header>
    </div>
</body>
<script>
    const { ref, createApp, computed } = Vue;
    const app = createApp({
        setup() {
            return {}
        }
    })

    const a = {
        setup(props) {
            let rate = ref(-1)

            function showB(index) {
                rate.value = index;
                const stars = document.querySelectorAll('.star')
                stars.forEach((star, i) => {
                    star.src = i <= rate.value ? './x2.png' : './xx.png';
                })
            }

            function showA(index, isHover) {
                const stars = document.querySelectorAll('.star')
                stars.forEach((star, i) => {
                    star.src = (rate.value !== -1 && i <= rate.value) || isHover && i <= index ? './x2.png' : './xx.png';
                })
            }

            function add() {
                if (rate.value < 4) {
                    rate.value++;
                    const stars = document.querySelectorAll('.star')
                    stars.forEach((star, i) => {
                        star.src = i <= rate.value ? './x2.png' : './xx.png';
                    })
                }
            }

            const text = computed(() => {
                const value = rate.value + 1;
                return value > 5 ? 5 : value;
            })

            return {
                rate,
                showB,
                showA,
                add,
                text
            }
        },
        template: `
            <div>
                <span>
                    <img class="star" src="./xx.png" alt="" @mouseover="showA(0, true)" @mouseout="showA(0, false)" @click="showB(0)">
                    <img class="star" src="./xx.png" alt="" @mouseover="showA(1, true)" @mouseout="showA(1, false)" @click="showB(1)">
                    <img class="star" src="./xx.png" alt="" @mouseover="showA(2, true)" @mouseout="showA(2, false)" @click="showB(2)">
                    <img class="star" src="./xx.png" alt="" @mouseover="showA(3, true)" @mouseout="showA(3, false)" @click="showB(3)">
                    <img class="star" src="./xx.png" alt="" @mouseover="showA(4, true)" @mouseout="showA(4, false)" @click="showB(4)">
                </span>
                <button @click="add">加一颗星</button>
                <p>点亮了 {{ text }} 颗星星。</p>
            </div>
        `
    }

    app.component('q-header', a)

    app.mount('#app')
</script>

</html>